<template>
    <div class="page-header">
        <div class="page-title">咨询师管理</div>
        <el-button type="primary" @click="showAddDialog = true">添加咨询师</el-button>
    </div>
    <div class="search-bar">
        <span>咨询师姓名：</span>
        <el-input v-model="searchQuery" style="width: 240px" placeholder="请输入咨询师姓名" />
        <el-button type="primary" @click="getList" class="search-btn">搜索</el-button>
        <el-button type="default" @click="resetSearch">重置</el-button>
    </div>
    <el-table :data="formattedTableData" @selection-change="handleSelectionChange" style="width: 100%"
        v-loading="loading">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="username" label="用户名" width="90" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="levelName" label="等级" width="130" />
        <el-table-column prop="avatar" label="头像" width="150">
            <template #default="scope">
                <div>
                    <img :src="scope.row.avatar" width="80px" height="80px" alt=""
                        @error="handleImageError(scope.row.avatar)">
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="aptitude" label="资质" width="90" />
        <el-table-column prop="region" label="地址" width="120" />
        <el-table-column label="专业领域" width="120">
            <template #default="scope">
                <span v-if="scope.row.expertiseFields.length > 0">
                    {{ scope.row.expertiseFields.join(', ') }}
                </span>
                <span v-else>无</span>
            </template>
        </el-table-column>
        <el-table-column label="证书" width="120">
            <template #default="scope">
                <span v-if="scope.row.certificates.length > 0">
                    {{ scope.row.certificates.join(', ') }}
                </span>
                <span v-else>无</span>
            </template>
        </el-table-column>
        <el-table-column label="是否认证" width="120">
            <template #default="scope">
                <el-tag :type="scope.row.isVerified ? 'primary' : 'danger'">
                    {{ scope.row.isVerified ? '已认证' : '未认证' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <view class="temp"></view>
    <el-pagination :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />


    <el-dialog v-model="showAddDialog" title="添加咨询师" @close="resetAddForm">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
<!--            <el-form-item label="ID" prop="id">-->
<!--                <el-input v-model="addForm.id" />-->
<!--            </el-form-item>-->
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="addForm.phone" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="addForm.sex">
                    <el-radio :label="0">男</el-radio>
                    <el-radio :label="1">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="头像：" label-width="100">
                <el-upload class="avatar-uploader" action="/api/oss/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="avatar" :src="avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="地址" prop="region">
                <el-input v-model="addForm.region" />
            </el-form-item>
            <el-form-item label="个人简介" prop="personalIntroduction">
                <el-input v-model="addForm.personalIntroduction" type="textarea" />
            </el-form-item>
            <el-form-item label="等级ID" prop="levelId">
                <el-input v-model="addForm.levelId" />
            </el-form-item>
            <el-form-item label="是否认证" prop="isVerified">
                <el-radio-group v-model="addForm.isVerified">
                    <el-radio :label="1">已认证</el-radio>
                    <el-radio :label="0">未认证</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否禁用" prop="isDisabled">
                <el-radio-group v-model="addForm.isDisabled">
                    <el-radio :label="1">已禁用</el-radio>
                    <el-radio :label="0">未禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="资质" prop="aptitude">
                <el-input v-model="addForm.aptitude" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑咨询师" @close="resetEditForm">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="120px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="editForm.sex">
                    <el-radio :label="0">男</el-radio>
                    <el-radio :label="1">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="头像：" label-width="100">
                <el-upload class="avatar-uploader" action="/api/oss/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="avatar" :src="avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="地址" prop="region">
                <el-input v-model="editForm.region" />
            </el-form-item>
            <el-form-item label="个人简介" prop="personalIntroduction">
                <el-input v-model="editForm.personalIntroduction" type="textarea" />
            </el-form-item>
            <el-form-item label="等级ID" prop="levelId">
                <el-input v-model="editForm.levelId" />
            </el-form-item>
            <el-form-item label="是否认证" prop="isVerified">
                <el-radio-group v-model="editForm.isVerified">
                    <el-radio :label="1">已认证</el-radio>
                    <el-radio :label="0">未认证</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否禁用" prop="isDisabled">
                <el-radio-group v-model="editForm.isDisabled">
                    <el-radio :label="1">已禁用</el-radio>
                    <el-radio :label="0">未禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="资质" prop="aptitude">
                <el-input v-model="editForm.aptitude" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button type="primary" @click="submitEditForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const avatar = ref('');
const handleAvatarSuccess = (response, uploadFile) => {
    console.log("+++++++++++++++");
    console.log("res",response);
    avatar.value = response;

    addForm.value.avatar = avatar.value;
    console.log(addForm.value.avatar);
}

// 定义表格数据
const tableData = ref([]);
// 定义选中的行
const multipleSelection = ref([]);
// 处理选择事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};
// 处理分页变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    getList();
};
// 处理每页显示数量变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    getList();
};
// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 处理搜索事件
const searchQuery = ref('');
function resetSearch() {
    searchQuery.value = '';
    getList();
}
// 定义获取表格数据的函数
async function getList() {
    try {
        const res = await axios.get(`/api/consultant/list`, {
            params: {
                username: searchQuery.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            }
        });
        console.log(res);
        tableData.value = res.data.data.list;
        total.value = res.data.data.total;
    } catch (error) {
        ElMessage.error('获取数据失败');
    }
}
// 计算属性：转换性别字段
const formattedTableData = computed(() => {
    return tableData.value.map(item => ({
        ...item,
        sex: item.sex === 0 ? '男' : '女'
    }));
});
// 添加表单相关数据
const showAddDialog = ref(false);
const addForm = ref({
    id: '',
    username: '',
    password: '',
    name: '',
    phone: '',
    sex: 0,
    avatar: '',
    region: '',
    personalIntroduction: '',
    levelId: '',
    isVerified: 0,
    isDisabled: 0,
    aptitude: ''
});
const addFormRef = ref(null);
const addFormRules = ref({
    // id: [
    //     { required: true, message: 'ID不能为空', trigger: 'blur' }
    // ],
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 20, message: '长度6 - 20个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '电话不能为空', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '性别不能为空', trigger: 'change' }
    ],
    avatar: [
        { required: true, message: '头像不能为空', trigger: 'blur' }
    ],
    region: [
        { required: true, message: '地址不能为空', trigger: 'blur' }
    ],
    personalIntroduction: [
        { required: true, message: '个人简介不能为空', trigger: 'blur' }
    ],
    levelId: [
        { required: true, message: '等级ID不能为空', trigger: 'blur' }
    ],
    isVerified: [
        { required: true, message: '是否认证不能为空', trigger: 'change' }
    ],
    isDisabled: [
        { required: true, message: '是否禁用不能为空', trigger: 'change' }
    ],
    aptitude: [
        { required: true, message: '资质不能为空', trigger: 'blur' }
    ]
});
async function submitAddForm() {
    try {
        await addFormRef.value.validate();
        const postData = {
            ...addForm.value
        };
        const res = await axios.post('/api/consultant/add', postData);
        if (res.data.code === 200) {
            ElMessage.success('添加成功');
            showAddDialog.value = false;
            getList();
            resetAddForm();
        }
    } catch (error) {
        ElMessage.error(error.response?.data?.msg || '添加失败');
    }
}
function resetAddForm() {
    addForm.value = {
        id: '',
        username: '',
        password: '',
        name: '',
        phone: '',
        sex: 0,
        avatar: '',
        region: '',
        personalIntroduction: '',
        levelId: '',
        isVerified: 0,
        isDisabled: 0,
        aptitude: ''
    };
}
// 编辑表单相关数据
const showEditDialog = ref(false);
const editForm = ref({
    id: null,
    username: '',
    sex: 0,
    avatar: '',
    region: '',
    personalIntroduction: '',
    levelId: '',
    isVerified: 0,
    isDisabled: 0,
    aptitude: ''
});
const editFormRef = ref(null);
function handleEdit(index, row) {
    editForm.value = {
        ...row,
        sex: row.sex === '男' ? 0 : 1
    };
    showEditDialog.value = true;
}
async function submitEditForm() {
    if (!editFormRef.value) {
        console.error('编辑表单ref未正确初始化');
        return;
    }
    try {
        await editFormRef.value.validate();
        const formData = {
            ...editForm.value,
            avatar: avatar.value
        };

        console.log('提交的数据:', formData);
        const res = await axios.post('/api/consultant/update', formData);
        if (res.data.code === 200) {
            ElMessage.success('编辑成功');
            showEditDialog.value = false;
            getList();
            resetEditForm();
            avatar.value=""
        }
    } catch (error) {
        console.log('错误响应:', error.response);
        ElMessage.error(error.response?.data?.msg || '编辑失败');
    }
}
function resetEditForm() {
    editForm.value = {
        id: null,
        username: '',
        sex: 0,
        avatar: '',
        region: '',
        personalIntroduction: '',
        levelId: '',
        isVerified: 0,
        isDisabled: 0,
        aptitude: ''
    };
}
const handleDelete = async (index, row) => {
    const confirmResult = await ElMessageBox.confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    try {
        const res = await axios.post('/api/consultant/delete?id=' + row.id);
        if (res.data.code === 200) {
            ElMessage.success('删除成功');
            getList();
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        ElMessage.error('删除失败');
    }

};
onMounted(() => {
    getList();
});
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 5px;
    border-bottom: 1px solid #ccc;
}

.page-title {
    font-weight: bold;
    padding-bottom: 10px;
}

.search-bar {
    margin: 10px 0;
    display: flex;
    align-items: center;
}

.search-btn {
    margin-left: 10px;
}

.temp {
    margin: 5px;
}

.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.avatar-uploader ::v-deep(.el-upload) {
    border: 1px dashed #8c939d;
    /* 修改边框颜色为灰色 */
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader ::v-deep(.el-upload):hover {
    border-color: #409EFF;
    /* 可选：鼠标悬停时的颜色 */
}

.avatar-uploader ::v-deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #196fe7;
    /* 修改图标颜色为灰色 */
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>